package cn.com.hhrcw.conferenceRoom.web;

import cn.com.hhrcw.conferenceRoom.entity.ConferenceRoom;
import cn.com.hhrcw.conferenceRoom.mapstruct.ConferenceRoomConvert;
import cn.com.hhrcw.conferenceRoom.params.ConferenceRoomParams;
import cn.com.hhrcw.conferenceRoom.service.IConferenceRoomService;
import cn.com.hhrcw.conferenceRoom.vo.ConferenceRoomVO;
import cn.com.hhrcw.service.HuaWeiRoomService;
import cn.com.hhrcw.utils.huawei.CreateMeetingParam;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

/**
* 会议室
* @module hhrcw-admin
* @author shengli
* @since 2021-09-18
*/
@RestController
@Slf4j
@RequestMapping("/admin/conferenceRoom")
@Validated
public class ConferenceRoomController extends JeecgController<ConferenceRoom, IConferenceRoomService> {

    @Autowired
    private IConferenceRoomService conferenceRoomService;

    @Autowired
    private ConferenceRoomConvert conferenceRoomConvert;


    /**
     * 分页列表查询
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/no_page_list")
    @AutoLog("会议室-无分页列表查询")
    public Result<List<ConferenceRoomVO>> noPagelist(ConferenceRoomParams params, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<ConferenceRoom> queryWrapper = QueryGenerator.initQueryWrapper(conferenceRoomConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        queryWrapper.isNotNull("conference_id");
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_platform", 1);
        List<ConferenceRoom> list = conferenceRoomService.list(queryWrapper);

        return Result.success(conferenceRoomConvert.toVO(list));
    }

    /**
     * 重新建立会议
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/rebuildRoom")
    public Result<?> rebuildRoom(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ConferenceRoom conferenceRoom = conferenceRoomService
                .lambdaQuery()
                .eq(ConferenceRoom::getId,id)
                .eq(ConferenceRoom::getDelFlag,false)
                .one();
        Assert.notNull(conferenceRoom, "数据不存在");
        try {
            conferenceRoom.setUpdateBy(sysUser.getRealname());
            conferenceRoom.setUpdateTime(new Date());
            conferenceRoomService.createMeeting(conferenceRoom);
            return Result.ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 分页列表查询
    * @param params 请求参数
    * @return
    */
    @GetMapping(value = "/list")
    @AutoLog("会议室-分页列表查询")
    public Result<Page<ConferenceRoomVO>> list(ConferenceRoomParams params, HttpServletRequest request) {
        QueryWrapper<ConferenceRoom> queryWrapper = QueryGenerator.initQueryWrapper(conferenceRoomConvert.toEntity(params), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        IPage<ConferenceRoom> page = conferenceRoomService.page(params.page(), queryWrapper);
        IPage<ConferenceRoomVO> convert = page.convert(e -> {
            ConferenceRoomVO vo = conferenceRoomConvert.toVO(e);
            vo.setIsExpire(false);
            if (vo.getEffectiveEndTime().before(new Date())) {
                vo.setIsExpire(true);
            }
            return vo;
        });
        return Result.success((Page) convert);
    }

    /**
    * 根据id查询
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/queryById")
    public Result<ConferenceRoomVO> queryById(String id) {
        ConferenceRoom conferenceRoom = conferenceRoomService
            .lambdaQuery()
            .eq(ConferenceRoom::getId,id)
            .eq(ConferenceRoom::getDelFlag,false)
            .one();
        Assert.notNull(conferenceRoom, "数据不存在");
        ConferenceRoomVO vo = conferenceRoomConvert.toVO(conferenceRoom);
        return Result.success(vo);
    }

    @Autowired
    private HuaWeiRoomService huaWeiRoomService;
    /**
    * 添加
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/add")
    @AutoLog("会议室-添加")
    public Result<?> add(@RequestBody @Valid ConferenceRoomParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ConferenceRoom one = conferenceRoomService.lambdaQuery()
                .eq(ConferenceRoom::getDelFlag, 0).eq(ConferenceRoom::getHuaweId, params.getHuaweId()).one();
        if (null != one) {
            return Result.error("会议室ID已存在，请勿重复创建！");
        }
        Boolean saved = false;
        try {
            if (params.getEffectiveEndTime().getTime() <= params.getEffectiveBeginTime().getTime()) {
                return Result.error("有效时间有误，请重新选择！");
            }
            ConferenceRoom conferenceRoom = conferenceRoomConvert.toEntity(params);
            conferenceRoom.setCreateBy(sysUser.getRealname());
            conferenceRoom.setCreateTime(new Date());
            conferenceRoom.setDelFlag(0);
            saved = conferenceRoomService.createMeeting(conferenceRoom);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
        return saved ? Result.ok() : Result.error("创建失败！");
    }

    /**
    * 编辑
    *
    * @param params 请求参数
    * @return
    */
    @PostMapping(value = "/edit")
    @AutoLog("会议室-编辑")
    public Result<?> edit(@RequestBody @Valid ConferenceRoomParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ConferenceRoom conferenceRoom = conferenceRoomConvert.toEntity(params);
        conferenceRoom.setUpdateBy(sysUser.getUsername());
        conferenceRoom.setUpdateTime(DateUtil.date());
        try {
            conferenceRoom.setUpdateBy(sysUser.getRealname());
            conferenceRoom.setUpdateTime(new Date());
            if (params.getEffectiveEndTime().getTime() <= params.getEffectiveBeginTime().getTime()) {
                return Result.error("有效时间有误，请重新选择！");
            }
            if (conferenceRoom.getStatus() == 0) {
                conferenceRoomService.cancelMeeting(conferenceRoom);
            } else {
                conferenceRoomService.createMeeting(conferenceRoom);
            }
            return Result.ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }


    /**
    * 批量删除
    *
    * @param id 数据id
    * @return
    */
    @GetMapping(value = "/delete")
    @AutoLog("会议室-批量删除")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<ConferenceRoom> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(ConferenceRoom::getId, id)
            .set(ConferenceRoom::getDelFlag, 1)
            .set(ConferenceRoom::getUpdateBy, sysUser.getUsername())
            .set(ConferenceRoom::getUpdateTime, DateUtil.date());
        boolean deleted = conferenceRoomService.update(updateWrapper);
        if (deleted) {
            for (String id1 : id) {
                ConferenceRoom oldRoom = this.conferenceRoomService.getById(id1);
                if (StrUtil.isNotBlank(oldRoom.getConferenceId())) {
                    Boolean canceld = huaWeiRoomService.cancelMeeting(oldRoom.getConferenceId());
                    if (canceld) {
                        this.conferenceRoomService.lambdaUpdate().eq(ConferenceRoom::getId, id1)
                                .set(ConferenceRoom::getHostUrl, null)
                                .set(ConferenceRoom::getPlayerUrl, null)
                                .set(ConferenceRoom::getMeetingId, null)
                                .set(ConferenceRoom::getConferenceId, null)
                                .set(ConferenceRoom::getUpdateBy, sysUser.getUsername())
                                .set(ConferenceRoom::getUpdateTime, DateUtil.date()).update();
                    }
                }
            }

        }
        return deleted ? Result.ok() : Result.error("删除失败");
    }


    /**
    * 导出excel
    *
    * @param request
    * @param params
    */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    public Result exportXls(HttpServletRequest request, ConferenceRoomParams params) {
        ConferenceRoom conferenceRoom = conferenceRoomConvert.toEntity(params);
        conferenceRoom.setDelFlag(0);
        QueryWrapper<ConferenceRoom> queryWrapper = QueryGenerator.initQueryWrapper(conferenceRoom, request.getParameterMap());
        List<ConferenceRoom> data = conferenceRoomService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("会议室", "会议室");
        String url = super.exportXls(exportParams, ConferenceRoomVO.class,conferenceRoomConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @PostMapping(value = "/importExcel")
        public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ConferenceRoom.class);
    }

}
